<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>新闻系统 - 用户注册</title>
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.1/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .register-card {
            max-width: 450px;
            margin: 3rem auto;
            box-shadow: 0 0 15px rgba(0,0,0,0.1);
            border-radius: 15px;
        }
        .captcha-refresh {
            cursor: pointer;
            transition: transform 0.3s;
        }
        .captcha-refresh:hover {
            transform: rotate(90deg);
        }
        .password-toggle {
            cursor: pointer;
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
        }
    </style>
</head>
<body class="bg-light">
    <div class="container">
        <div class="card register-card">
            <div class="card-body p-4">
                <h2 class="text-center mb-4">新闻系统注册</h2>
                
                <!-- 注册表单 -->
                <form id="registerForm" novalidate>
                    <!-- 账号输入 -->
                    <div class="mb-3">
                        <label for="username" class="form-label">账号</label>
                        <input 
                            type="text" 
                            class="form-control" 
                            id="username"
                            name="username"
                            required
                            placeholder="请输入账号"
                        >
                        <div class="invalid-feedback">请输入有效账号</div>
                    </div>

                    <!-- 密码输入 -->
                    <div class="mb-3 position-relative">
                        <label for="password" class="form-label">密码</label>
                        <input 
                            type="password" 
                            class="form-control pe-5" 
                            id="password" 
                            name="password"
                            required
                            placeholder="请输入密码"
                            minlength="6"
                        >
                        <i class="bi password-toggle" onclick="togglePassword()"></i>
                        <div class="invalid-feedback">密码至少6位</div>
                    </div>

                    <!-- 验证码 -->
                    <div class="mb-4">
                        <label class="form-label">验证码</label>
                        <div class="d-flex gap-2">
                            <div class="flex-grow-1">
                                <input 
                                    type="text" 
                                    class="form-control" 
                                    id="captchaResult"
                                    name="captchaResult"
                                    required
                                    placeholder="计算结果"
                                    inputmode="numeric"
                                >
                                <div class="invalid-feedback">请输入计算结果</div>
                            </div>
                            <div class="d-flex align-items-center gap-2">
                                <span id="captchaExp" class="fw-bold"></span>
                                <i class="bi bi-arrow-repeat captcha-refresh" onclick="generateCaptcha()"></i>
                            </div>
                        </div>
                    </div>

                    <!-- 注册按钮 -->
                    <button 
                        type="submit" 
                        class="btn btn-primary w-100"
                        id="registerBtn"
                    >
                        立即注册
                    </button>

                    <!-- 登录链接 -->
                    <div class="text-center mt-3">
                        <span>已有账号？</span>
                        <a href="/" class="btn btn-link p-0">立即登录</a>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Bootstrap 5 JS 及其依赖 -->
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.1/js/bootstrap.bundle.min.js"></script>
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/bootstrap-icons/1.10.3/font/bootstrap-icons.min.css">
    
    <!-- 自定义脚本 -->
    <script>
        // 密码显示切换
        function togglePassword() {
            const pwdInput = document.getElementById('password')
            const icon = document.querySelector('.password-toggle')
            if (pwdInput.type === 'password') {
                pwdInput.type = 'text'
                icon.classList.replace('bi-eye', 'bi-eye-slash')
            } else {
                pwdInput.type = 'password'
                icon.classList.replace('bi-eye-slash', 'bi-eye')
            }
        }

        // 初始化密码图标
        document.querySelector('.password-toggle').classList.add('bi-eye')

        // 生成随机验证码表达式
        let currentExpression = ''
        function generateCaptcha() {
            const operators = ['+', '-', '*']
            const a = Math.floor(Math.random() * 10) + 1  // 1-10
            const b = Math.floor(Math.random() * 10) + 1
            const op = operators[Math.floor(Math.random() * operators.length)]
            
            currentExpression = `${a} ${op} ${b}`
            document.getElementById('captchaExp').textContent = currentExpression
        }

        // 页面加载时生成初始验证码
        generateCaptcha()

        // 表单提交处理
        document.getElementById('registerForm').addEventListener('submit', async (e) => {
            e.preventDefault()
            const form = e.target
            const btn = document.getElementById('registerBtn')
            
            if (!form.checkValidity()) {
                form.classList.add('was-validated')
                return
            }

            try {
                // 禁用按钮
                btn.disabled = true
                btn.innerHTML = `
                    <span class="spinner-border spinner-border-sm"></span>
                    注册中...
                `

                // 构造数据
                const payload = {
                    name: document.getElementById('username').value.trim(),
                    passwd: document.getElementById('password').value,
                    result: document.getElementById('captchaResult').value,
                    exp: currentExpression
                }

                // 发送请求
                const response = await fetch('/register', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(payload)
                })

                if (!response.ok) {
                    const error = await response.json()
                    throw new Error(error.message || '注册失败')
                }

                alert('注册成功！即将跳转到登录页面...')
                window.location.href = '/'
                
            } catch (error) {
                // 重新生成验证码
                generateCaptcha()
                document.getElementById('captchaResult').value = ''
                
                // 显示错误
                alert(error.message || '注册请求失败，请检查网络')
            } finally {
                // 恢复按钮
                btn.disabled = false
                btn.innerHTML = '立即注册'
            }
        })
    </script>
</body>
</html>